package com.rope.backEnd.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rope.backEnd.pojo.ChatRequest;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Service
@RequiredArgsConstructor
public class ChatService {
    private final OkHttpClient client;
    private final Request.Builder requestBuilder;

    public void streamChatCompletion(ChatRequest request, SseEmitter emitter) throws IOException {
        RequestBody body = RequestBody.create(
                new ObjectMapper().writeValueAsString(request),
                MediaType.get("application/json")
        );

        Request httpRequest = requestBuilder
                .url("https://api.deepseek.com/v1/chat/completions")
                .post(body)
                .build();

        client.newCall(httpRequest).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(responseBody.byteStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data: ")) {
                            String data = line.substring(6);
                            if (!"[DONE]".equals(data)) {
                                emitter.send(data);
                            }
                        }
                    }
                    emitter.complete();
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                emitter.completeWithError(e);
            }
        });
    }
}
